package meblog.online.server.utils;

import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.LongAdder;

/**
 * @author yuelong
 * @description 线程相关
 */
public class ThreadUtil {

    static public class CustomThreadFactory implements ThreadFactory {

        /**
         * 线程池名称
         */
        private final String prefix;

        private final LongAdder threadNumber = new LongAdder();

        public CustomThreadFactory(String prefix) {
            this.prefix = prefix;
        }

        @Override
        public Thread newThread(Runnable runnable) {
            threadNumber.add(1);
            return new Thread(runnable, prefix + " => " + threadNumber.intValue());
        }
    }

    /**
     * 获取netty的工作线程池, 通过自定义的线程工厂设置线程池名字
     * @param size
     * @param name
     * @return
     */
    public static EventLoopGroup getEventLoop(int size, String name) {
        return new NioEventLoopGroup(size, new CustomThreadFactory(name));
    }

    /**
     * 重载方法，默认是0，netty会自定义核心线程数
     * @param name
     * @return
     */
    public static EventLoopGroup getEventLoop(String name) {
        return getEventLoop(0, name);
    }

}
